import gc
from machine import SPI, Pin
from drivers import vs1003


class UDPServer:
	_WAVE_HEADER_1 = bytes([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6D, 0x74, 0x20,
	                        0x12, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x40, 0x1F, 0x00, 0x00, 0x80, 0x3E, 0x00, 0x00])
	_WAVE_HEADER_2 = bytes([0x02, 0x00, 0x10, 0x00, 0x00, 0x00, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00])
	# _WAVE_HEADER_1 = bytes([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20,
	# 						0x14, 0x00, 0x00, 0x00, 0x11, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x75, 0x12, 0x00, 0x00])
	# _WAVE_HEADER_2 = bytes([0x00, 0x01, 0x04, 0x00, 0x02, 0x00, 0xf9, 0x01, 0x66, 0x61, 0x63, 0x74, 0x04, 0x00, 0x00, 0x00,
	# 						0x5c, 0x1f, 0x00, 0x00, 0x64, 0x61, 0x74, 0x61, 0xe8, 0x0f, 0x00, 0x00])

	def __init__(self, host, port, player, callback: callable()):
		import socket
		from config import Config
		from wifihandler import WifiHandler

		host = socket.getaddrinfo(host, port)[0][-1]

		self._player = player
		self._callback = callback
		self._is_running = False
		self._server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self._server.bind(host)

		# self._mac_address = WifiHandler.get_mac_address(WifiHandler.STA_MODE)

		print("udp server bind on %s:%s" % (host[0], host[1]))

		self._player.reset()

		self._player.play_chunk(self._WAVE_HEADER_1)
		self._player.play_chunk(self._WAVE_HEADER_2)

	def start(self):
		from utime import sleep_ms

		# self._is_running = True

		print("starting receiving data")

		while True:  # self._is_running:
			# sleep_ms(300)

			data, addr = self._server.recvfrom(52)

			if not data:
				continue

			data = data[20:]

			# print(data)

			self._player.play_chunk(data)

			# print(data[20:])
			# self._player.play_chunk(data[20:])
			# self._callback(data)

			# request = str(data, "utf-8").strip()
			#
			# if len(request) == 0:
			# 	continue
			#
			# print("received udp request: {0} [{1}:{2}]".format(request, address[0], address[1]))

			# self._respond_to_client(address, request)

			# gc.collect()

	def stop(self):
		self._is_running = False
